package com.booktrading.controller;

import com.booktrading.model.CategoryOrderStat;
import com.booktrading.model.User;
import com.booktrading.service.OrderService;
import com.booktrading.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.booktrading.model.AdminLog;
import com.booktrading.service.AdminLogService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@Controller
public class AdminController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OrderService orderService;

    @Autowired
    private AdminLogService adminLogService;

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public String adminPage() {
        return "admin";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/user")
    public String adminUser(Model model) {
        List<User> userList = userService.getAllUsers();
        model.addAttribute("userList", userList);
        return "admin_user";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/stats")
    public String adminStats(Model model) {
        int orderCount = orderService.countAll();
        Double totalAmount = orderService.sumAllAmount();
        List<CategoryOrderStat> categoryStats = orderService.countByCategory();
        model.addAttribute("orderCount", orderCount);
        model.addAttribute("totalAmount", totalAmount);
        model.addAttribute("categoryStats", categoryStats);
        return "admin_stats";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/log")
    public String adminLog(Model model) {
        model.addAttribute("logList", adminLogService.getAllLogs());
        return "admin_log";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/user/status")
    @ResponseBody
    public String updateUserStatus(@RequestParam Long userId, @RequestParam Integer status) {
        boolean result = userService.updateUserStatus(userId, status);
        if (result) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String adminName = auth.getName();
            User admin = userService.getUserByUsername(adminName);
            User targetUser = userService.getUserById(userId);
            AdminLog log = new AdminLog();
            log.setAdminId(admin.getId());
            log.setAdminName(admin.getUsername());
            log.setAction(status == 0 ? "禁用用户" : "恢复用户");
            log.setTargetUserId(targetUser.getId());
            log.setTargetUsername(targetUser.getUsername());
            log.setDetail("管理员" + admin.getUsername() + (status == 0 ? "禁用了" : "恢复了") + "用户" + targetUser.getUsername());
            adminLogService.insert(log);
        }
        return result ? "success" : "fail";
    }
} 